import base64
import urllib
import requests
import json
import cv2
import numpy as np

apikey="EO8531qaS2w7p1WQOTnlslYZ"
secretkey="PwiyJITOASccm1Ph6LUWvtlzEOWkeqDp"

def AIBaiDu_handwriting_POST(image, key, secret):
    # 读取图片并转换为 base64
    
    image_base64 = get_file_content_as_base64(image,True) 
    
    # 设置 API URL，注意这里的 access_token 需要替换为你实际获取的 token
    api_url =  "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token=" + get_access_token(key, secret)

    payload = 'image=' + image_base64 + '&detect_direction=false&probability=false&detect_alteration=false'

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    # 发送 POST 请求
    response = requests.request("POST", api_url, headers=headers, data=payload)
   
    if response.status_code == 200:
        result = response.json()
        if 'words_result' in result:
            # 直接使用 result['words_result'] 而不是将其赋值给 data 变量
            words = '\n'.join([item['words'] for item in result['words_result']])
            return words
        else:
            error_msg = "Response format error: 'words_result' key missing."
            print(error_msg)
            return error_msg
    else:
        error_response = response.json()
        error_msg = error_response.get('error_msg', 'Unknown error')
        print(f"Error occurred: {error_msg}")
        return error_msg

def capture_and_recognize_text(apikey, secretkey):
    global selecting, top_left, bottom_right, roi, frame
    selecting = False
    top_left = (-1, -1)
    bottom_right = (-1, -1)
    roi = None

    # 初始化摄像头
    cap = cv2.VideoCapture(0)

    if not cap.isOpened():
        print("Cannot open camera")
        exit()

    # 设置鼠标回调函数
    cv2.namedWindow('frame')
    cv2.setMouseCallback('frame', select_roi)

    while True:
        # 捕获一帧
        ret, frame = cap.read()

        # 如果正确读取帧，ret 将为 True
        if not ret:
            print("Failed to grab frame")
            break

        # 显示捕获的画面
        if selecting:
            cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 2)

        cv2.imshow('frame', frame)

        # 按 'q' 键退出循环
        if cv2.waitKey(1) & 0xFF == ord('q') or roi is not None:
            break

    # 当一切完成时释放捕获器
    cap.release()
    cv2.destroyAllWindows()

    # 确保有有效的 ROI
    if roi is not None:
        # 将捕获的 ROI 保存为临时文件
        cv2.imwrite('temp.jpg', roi)
        
    
        return 'temp.jpg'
    else:
        return "No valid region selected."

def get_access_token(API_KEY, SECRET_KEY):
    """
    使用 AK,SK 生成鉴权签名(Access Token)
    :return: access_token,或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content

def select_roi(event, x, y, flags, param):
    global roi, selecting, top_left, bottom_right, frame

    # 开始选择区域
    if event == cv2.EVENT_LBUTTONDOWN:
        selecting = True
        top_left = (x, y)

    # 移动鼠标时更新右下角坐标
    elif event == cv2.EVENT_MOUSEMOVE and selecting:
        bottom_right = (x, y)

    # 结束选择区域
    elif event == cv2.EVENT_LBUTTONUP:
        selecting = False
        bottom_right = (x, y)
        roi = frame[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]]

